package com.qiantu.phone.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;
import android.view.ViewConfiguration;

import com.qiantu.phone.R;
import com.qiantu.phone.app.AppApplication;

public class StatusSeekBar extends View {

    private float mTouchDownX;
    private float mTouchDownY;
    private int mScaledTouchSlop;
    private Drawable progressTextBg;
    private String unit;
    // 画笔
    private Paint mPaint;
    private Paint mTextPaint;
    private Paint mThumbPaint;
    // 滑块按钮宽度
    private float mThumbWidth;
    private float mThumbStrokeWidth;
    private float mThumbHeight;
    private float progressTextSize;
    private int progressTextColor;
    private float progressTextMarginTop;
    private float progressTextBgMarginBottom;
    private float leftRightTextMarginTop;
    private float progressTrackHeight;
    private int progressTrackStartColor;
    private int progressTrackEndColor;
    private float leftRightTextSize;
    private int leftRightTextColor;
    private int progressTextHeight;
    private int progressTextHolderHeight;
    private int bottomLeftRightTextHeight;
    private int bottomLeftRightTextHolderHeight;
    private String progressText = null;
    private float progress;
    private float canSlideTotalWidth;
    private OnSeekBarChangeListener mOnSeekBarChangeListener;
    private boolean isOverTouchSlop;
    private float thumbCx;
    private boolean isOnlyClick = false;
    private long lastDownTime;
    private float slidDistance;
    private boolean isFirst;
    private RectF mBarRectF;
    private RectF mThumbRectF;
    private int[] gradientColors;
    private LinearGradient mLinearGradient;
    private float mThumbLeftRightOffset;
    //可拖范围加个偏移
    private int mThumbDragOffset;
    private int minValue;
    private int maxValue;
    private float totalProgress;
    private int mTemp;

    public StatusSeekBar(Context context) {
        this(context, null);
    }

    public StatusSeekBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public StatusSeekBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray ta = attrs == null ? null : getContext().obtainStyledAttributes(attrs, R.styleable.TemperatureSeekBar);
        if (ta != null) {
            mThumbWidth = ta.getDimension(R.styleable.TemperatureSeekBar_temperature_seek_bar_progress_thumb_width, dp2px(26));
            mThumbHeight = ta.getDimension(R.styleable.TemperatureSeekBar_temperature_seek_bar_progress_thumb_height, dp2px(26));
            progressTrackHeight = ta.getDimension(R.styleable.TemperatureSeekBar_temperature_seek_bar_progress_track_height, dp2px(12));
            progressTrackStartColor = ta.getColor(R.styleable.TemperatureSeekBar_temperature_seek_bar_progress_track_start_color, dp2px(12));
            progressTrackEndColor = ta.getColor(R.styleable.TemperatureSeekBar_temperature_seek_bar_progress_track_end_color, dp2px(12));
            progressTextSize = ta.getDimension(R.styleable.TemperatureSeekBar_temperature_seek_bar_progress_text_size, dp2px(12));
            progressTextColor = ta.getColor(R.styleable.TemperatureSeekBar_temperature_seek_bar_progress_text_color, AppApplication.getInstance().getThemeColor(R.attr.textColor4));
            progressTextBg = ta.getDrawable(R.styleable.TemperatureSeekBar_temperature_seek_bar_progress_text_bg);
            minValue = ta.getInt(R.styleable.TemperatureSeekBar_temperature_seek_bar_min, -20);
            maxValue = ta.getInt(R.styleable.TemperatureSeekBar_temperature_seek_bar_max, 45);
            unit = ta.getString(R.styleable.TemperatureSeekBar_temperature_seek_bar_unit);
            leftRightTextSize = ta.getDimension(R.styleable.TemperatureSeekBar_temperature_seek_bar_left_right_text_size, dp2px(10));
            leftRightTextColor = ta.getColor(R.styleable.TemperatureSeekBar_temperature_seek_bar_left_right_text_color, AppApplication.getInstance().getThemeColor(R.attr.textColor2));
            progressTextMarginTop = ta.getDimension(R.styleable.TemperatureSeekBar_temperature_seek_bar_progress_text_margin_top, dp2px(11));
            progressTextBgMarginBottom = ta.getDimension(R.styleable.TemperatureSeekBar_temperature_seek_bar_progress_text_bg_margin_bottom, dp2px(8));
            leftRightTextMarginTop = ta.getDimension(R.styleable.TemperatureSeekBar_temperature_seek_bar_left_right_text_margin_top, dp2px(4));
        }
        mThumbStrokeWidth = dp2px(4);
        mScaledTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
        mBarRectF = new RectF();
        mThumbStrokeWidth = getResources().getDimensionPixelSize(R.dimen.dp_2);
        mThumbDragOffset = getResources().getDimensionPixelSize(R.dimen.dp_10);
        gradientColors = new int[]{progressTrackStartColor, progressTrackEndColor};
        getTotalProgress();
        init();
    }

    private void init() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);

        mTextPaint = new TextPaint();
        mTextPaint.setAntiAlias(true);

        mThumbPaint = new Paint();
        mThumbPaint.setStrokeWidth(mThumbStrokeWidth);
        mThumbPaint.setAntiAlias(true);

        if (progressTextBg != null && progressTextBg.getIntrinsicWidth() != 0 && progressTextBg.getIntrinsicHeight() != 0) {
            progressTextHolderHeight = (int) (progressTextBg.getIntrinsicHeight() + progressTextBgMarginBottom);
            int progressTextHolderWidth = progressTextBg.getIntrinsicWidth();
            mThumbLeftRightOffset = progressTextHolderWidth/ 2f;
        } else {
            mTextPaint.setTextSize(progressTextSize);
            Paint.FontMetrics fontMetrics = mTextPaint.getFontMetrics();
            progressTextHeight = (int) (fontMetrics.bottom - fontMetrics.top);
            progressTextHolderHeight = (int) (progressTextHeight + progressTextBgMarginBottom);
            int progressTextHolderWidth = (int) Math.max(mTextPaint.measureText(minValue + unit), mTextPaint.measureText(maxValue + unit));
            mThumbLeftRightOffset = progressTextHolderWidth/ 2f;
        }
        mTextPaint.setTextSize(leftRightTextSize);
        Paint.FontMetrics fontMetrics = mTextPaint.getFontMetrics();
        bottomLeftRightTextHeight = (int) (fontMetrics.bottom - fontMetrics.top);
        bottomLeftRightTextHolderHeight = (int) (bottomLeftRightTextHeight + leftRightTextMarginTop);

        mThumbRectF = new RectF();
    }

    public void setMinMaxValue(int minValue, int maxValue) {
        this.minValue = minValue;
        this.maxValue = maxValue;
        getTotalProgress();
    }

    public void setUnitValue(String unit) {
        this.unit = unit;
    }

    private void getTotalProgress() {
        totalProgress = (maxValue - minValue);
    }

    public void setGradientColors(int[] gradientColors) {
        this.gradientColors = gradientColors;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!isEnabled()) {
            return false;
        }
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastDownTime = System.currentTimeMillis();
                isFirst = true;
                mTouchDownX = event.getX();
                mTouchDownY = event.getY();
                //只有Thumb区域可以点击拖动
                if (mTouchDownX >= thumbCx - mThumbWidth / 2f - mThumbDragOffset && mTouchDownX <= thumbCx + mThumbWidth / 2f + mThumbDragOffset
                    && event.getY() >= progressTextHolderHeight && event.getY() - mThumbDragOffset <= progressTextHolderHeight + mThumbHeight + mThumbDragOffset) {
                    //圆点之内可以拖动
                    isOnlyClick = false;
                } else {
                    //圆点之外只能点击
                    isOnlyClick = true;
                }
                //已滑动距离
                slidDistance = progress * canSlideTotalWidth;
                //重置, 触摸中不进行ScaledTouchSlop判断
                isOverTouchSlop = false;
                break;
            case MotionEvent.ACTION_MOVE:
                final float x = event.getX();
                float distance = x - mTouchDownX;
                if (!isOnlyClick
//                        && System.currentTimeMillis() - lastDownTime > 200
//                        && (Math.abs(distance) >= mScaledTouchSlop || isOverTouchSlop)
                ) {
                    if (isFirst) {
                        isFirst = false;
//                        setAlpha(0.8f);
                        if (mOnSeekBarChangeListener != null) {
                            mOnSeekBarChangeListener.onStartTrackingTouch();
                        }
                    }
                    getParent().requestDisallowInterceptTouchEvent(true);
                    Log.i("luzx", "Math.abs(distance) > mScaledTouchSlop:" + Math.abs(distance) + ">=" + mScaledTouchSlop);
                    isOverTouchSlop = true;
                    progress = (distance + slidDistance) / canSlideTotalWidth;
                    progress = progress < 0 ? 0 : progress;
                    progress = progress >= 0.995 ? 1 : progress;
                    Log.i("luzx", "progress" + progress);
                    calculateTemp();
                    invalidate();
                    if (mOnSeekBarChangeListener != null) {
                        mOnSeekBarChangeListener.onValueChanged(mTemp);
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                //点击
                float upX = event.getX();
                float upY = event.getY();
                float clickDistance = (float) Math.sqrt(Math.pow(Math.abs(upX - mTouchDownX), 2) + Math.pow(Math.abs(upY - mTouchDownY), 2));
                if (clickDistance <= dp2px(2)) {
                    progress = (event.getX() - mThumbLeftRightOffset) / canSlideTotalWidth;
                    progress = progress < 0 ? 0 : progress;
                    progress = progress >= 0.995 ? 1 : progress;
                    Log.i("luzx", "progress" + progress);
                    calculateTemp();
                    invalidate();
                }
                getParent().requestDisallowInterceptTouchEvent(false);
                if (mOnSeekBarChangeListener != null) {
                    playSoundEffect(SoundEffectConstants.CLICK);
                    mOnSeekBarChangeListener.onStopTrackingTouch(mTemp);
                }
//                setAlpha(1f);
                break;
            case MotionEvent.ACTION_CANCEL:
//                getParent().requestDisallowInterceptTouchEvent(false);
//                if (mOnSeekBarChangeListener != null) {
//                    mOnSeekBarChangeListener.onStopTrackingTouch(progressStep100);
//                }
//                setAlpha(1f);
                break;
        }
        return true;
    }

    private void calculateTemp() {
        mTemp = (int) Math.round(progress * totalProgress) + minValue;
        mTemp = mTemp < minValue ? minValue : mTemp;
        mTemp = mTemp > maxValue ? maxValue : mTemp;
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        mPaint.setShader(mLinearGradient);
        canvas.drawRoundRect(mBarRectF, progressTrackHeight, progressTrackHeight, mPaint);
        mPaint.setShader(null);

        thumbCx = mThumbLeftRightOffset + (canSlideTotalWidth * progress);
        mThumbPaint.setColor(0xffffffff);
        mThumbPaint.setStyle(Paint.Style.FILL);
        mThumbRectF.left = thumbCx - mThumbWidth / 2f + (mThumbStrokeWidth / 2f);
        mThumbRectF.top = progressTextHolderHeight + (mThumbStrokeWidth / 2f);
        mThumbRectF.right = thumbCx + mThumbWidth / 2f - (mThumbStrokeWidth / 2f);
        mThumbRectF.bottom = mThumbRectF.top + mThumbHeight - (mThumbStrokeWidth / 2f);
        canvas.drawRoundRect(mThumbRectF, mThumbWidth, mThumbWidth, mThumbPaint);
        mThumbPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
        mThumbPaint.setStyle(Paint.Style.STROKE);
        canvas.drawRoundRect(mThumbRectF, mThumbWidth, mThumbWidth, mThumbPaint);

        int progressTextBgLeft = (int) (thumbCx - progressTextBg.getIntrinsicWidth() / 2);
        int progressTextBgRight = (int) (thumbCx + progressTextBg.getIntrinsicWidth() / 2);
        if (progressTextBg != null) {
            progressTextBg.setBounds(progressTextBgLeft, 0, progressTextBgRight, progressTextBg.getIntrinsicHeight());
        }

        mTemp = mTemp == 0 ? minValue : mTemp;
        progressTextBg.draw(canvas);
        progressText = mTemp + unit;
        mTextPaint.setTextSize(progressTextSize);
        mTextPaint.setColor(progressTextColor);
        int textX = (int) (thumbCx - mTextPaint.measureText(progressText) / 2);
        canvas.drawText(progressText, textX, -mTextPaint.getFontMetrics().ascent + progressTextMarginTop, mTextPaint);

        mTextPaint.setTextSize(leftRightTextSize);
        mTextPaint.setColor(leftRightTextColor);
        String leftText = minValue + unit;
        canvas.drawText(leftText, mThumbLeftRightOffset, getHeight() - mTextPaint.getFontMetrics().descent, mTextPaint);

        String rightText = maxValue + unit;
        canvas.drawText(rightText, getWidth() - mTextPaint.measureText(rightText) - mThumbLeftRightOffset, getHeight() - mTextPaint.getFontMetrics().descent, mTextPaint);
    }

    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int dw = getMeasuredWidth();
        int dh = (int) (progressTextHolderHeight + mThumbHeight + bottomLeftRightTextHolderHeight);
        setMeasuredDimension(dw, dh);
        mBarRectF.left = mThumbLeftRightOffset;
        mBarRectF.right = dw - mThumbLeftRightOffset;
        mBarRectF.top = progressTextHolderHeight + (mThumbHeight - progressTrackHeight) / 2f;
        mBarRectF.bottom = mBarRectF.top + progressTrackHeight;
        mLinearGradient = new LinearGradient(0, 0, dw, 0, gradientColors, null, Shader.TileMode.CLAMP);
        canSlideTotalWidth = mBarRectF.width();
    }

//    public void setProgress(int progress) {
//        progress = progress > 100 ? 100 : progress;
//        this.progress = progress / 100f;
//        progressStep100 = (int) (this.progress * totalProgress + 0.5f);
//        invalidate();
//    }

    public void setValue(int temp) {
        mTemp = temp;
        progress = (Float.valueOf(mTemp) - minValue) / totalProgress;
        progress = progress < 0 ? 0 : progress;
        progress = progress > 1 ? 1 : progress;
        invalidate();
    }

    public int getTemp() {
        return mTemp;
    }

    /**
     * 进度监听
     */
    public interface OnSeekBarChangeListener {
        /**
         * 进度监听回调
         *
         * @param value
         */
        public void onValueChanged(int value);

        /**
         * 开始拖动
         */
        public void onStartTrackingTouch();

        /**
         * 停止拖动
         */
        public void onStopTrackingTouch(int value);
    }

    public void setOnSeekBarChangeListener(OnSeekBarChangeListener changeListener) {
        this.mOnSeekBarChangeListener = changeListener;
    }

    /**
     * dp转px
     *
     * @param dp dp值
     * @return px值
     */
    public int dp2px(float dp) {
        return (int) (getResources().getDimension(R.dimen.dp_1) * dp);
    }
}
